import axios from 'axios'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // 从axios的data中解构出来必要的字段
    const { success, message, data } = response.data
    // 如果success为true,直接返回data即可
    if (success) {
      return data
    } else {
      // console.log(Promise.reject(new Error(message)))
      // 如果success为false 业务出错,直接触发reject 被catch分支捕获
      return Promise.reject(new Error(message))
    }
  }, error => {
    if (error.response.status === 401) {
      console.log(error)
      // 当等于10002的时候 表示 后端告诉我token超时
      store.commit('user/removeUserInfo') // 登出action 删除token
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
